var upte_callback = null;

window.upte_translateText = function(response) { 
  if (upte_callback) {
    upte_callback(response.data.translations[0].translatedText);
  } else {
    console.log("upset: callback is empty, not calling a callback");
  }
}

function UnofficialPlusTranslateExtension() {
}

UnofficialPlusTranslateExtension.prototype.getElementsByClassName = function(classname) {
    var node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for (var i=0, j=els.length; i<j; i++)
        if (re.test(els[i].className)) a.push(els[i]);
    return a;
};


UnofficialPlusTranslateExtension.prototype.isTranslated = function(div) {
  if (!this.translated) this.translated = [];
  for (var i = 0; i < this.translated.length; i++) {
    if (this.translated[i] == div) return true;
  }
  return false;
};
  


UnofficialPlusTranslateExtension.prototype.DoJob = function() {
  var divs = this.getElementsByClassName("a-b-f-i-p-R");
  console.log("upte: processing " + divs.length + " divs");
  for (var i = 0; i < divs.length; i++) {
    if (this.isTranslated(divs[i])) continue;
    this.translate(divs[i]);
    this.translated.push(divs[i]);
  }
  setTimeout(upte_iterate, 3000);
};

UnofficialPlusTranslateExtension.prototype.callTranslateAPI = function(text, callback) {
  chrome.extension.sendRequest(text, callback);
};

UnofficialPlusTranslateExtension.prototype.translate = function(element) {
  var content = element.innerHTML;
  console.log("upte: sending translate request");
  this.callTranslateAPI(content, function(response) {
      console.log("upte: got translate response");
      if (response.detectedSourceLanguage == "en" || response.translation.length == 0) return;
      element.innerHTML = "<span style='background:#096;color:#fff;margin-right:10px'>translated</span>" + 
                response.translation;
  });
};


var upte_object = new UnofficialPlusTranslateExtension();
var upte_iterate = function() {upte_object.DoJob();};
setTimeout(upte_iterate, 3000);



